<template>
  <div>
    <json-editor ref="editor" :json="formConfig" :options="formJsonEditorOptions" />
  </div>
</template>

<script>
import JsonEditor from '@/components/JsonEditor/json-editor'
import { saveData, getMenuConfig } from '@/api/menu'

var _this
export default {
  name: 'FormConfig',
  components: { JsonEditor },
  props: {
    menuId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      queryBtnDialog: false,
      formConfig: this.formConfigTemp(),
      formJsonEditorOptions: {
        mode: 'code'
      }
    }
  },
  watch: {
    menuId() {
      this.initConfig()
    }
  },
  created() {
    _this = this
    this.initConfig()
  },
  methods: {
    initConfig() {
      getMenuConfig(this.menuId).then(res => {
        const { data } = res
        _this.formConfig = (data && data.formConfig && JSON.parse(data.formConfig)) || JSON.parse(this.formConfigTemp())
      })
    },
    addQueryBtn() {

    },
    formConfigTemp() {
      return `
        {
          "dialog": {
            "width": "50%"
          },
          "detail": {
            "request": {
              "url": ""
            }
          },
          "form": {
            "request": {
              "url": "",
              "method": "post"
            },
            "rows": [
              {
                "gutter": 20,
                "cols": [
                  {
                    "span": 20,
                    "label": "",
                    "type": "input",
                    "name": "",
                    "rule": [
                      {
                        "required": true,
                        "message": "请输入",
                        "trigger": "change"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        }
      `
    },
    save() {
      try {
        this.formConfig = this.$refs.editor.editor.get()
      } catch (e) {
        this.$message.error('保存失败，请检查json格式')
        return
      }
      saveData({
        id: this.menuId,
        formConfig: JSON.stringify(this.formConfig)
      }).then(res => {
        _this.$emit('save-callback')
      })
    }
  }
}
</script>

<style>
  .h3-title {
    border-left: 5px solid #0092EE;padding-left: 10px
  }
  .el-dialog__body {
    padding: 0px 20px;
  }
</style>
